package com.sunday.pinxinghui.model.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Fans;
import com.sunday.pinxinghui.entity.Product;
import com.sunday.pinxinghui.model.products.ProductDetailActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/11.
 */

public class CollectionListActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private LinearLayoutManager layoutManager;
    private CommonAdapter<Product> adapter;
    private List<Product> dataSet = new ArrayList<>();
    private int pageNo = 1, lastVisibleItem;
    private boolean isCanloadMore;
    private long productId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_list);
        ButterKnife.bind(this);
        titleView.setText("我的收藏");
        productId = getIntent().getLongExtra("productId", 0);
        initRecyclerView();
        getData();
    }

    private void initRecyclerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<Product>(mContext, R.layout.list_product_collection, dataSet) {
            @Override
            public void convert(ViewHolder holder, Product product, int position) {
                bind(holder, product, position);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });
    }

    private void bind(ViewHolder productHolder, final Product item, final int position) {

        ImageView productImg = productHolder.getView(R.id.product_img);
        if (!TextUtils.isEmpty(item.getImage())) {
            Glide.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_default)
                    .into(productImg);
        }
        ((TextView) productHolder.getView(R.id.product_title)).setText(item.getProductName());
        ((TextView) productHolder.getView(R.id.sale_num)).setText("销量" + item.getSaleCount());
        ((TextView) productHolder.getView(R.id.price_old)).setText(String.format("市价¥%s", item.getCostPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) productHolder.getView(R.id.price_old)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        switch (item.getType()) {
            case 1:
                //普通商品
                ((ImageView) productHolder.getView(R.id.flag_img)).setVisibility(View.GONE);
                ((TextView) productHolder.getView(R.id.price_now)).setText(String.format("会员价:¥%s", item.getVipPrice().setScale(2, RoundingMode.HALF_UP)));
                break;
            case 2:
                //秒杀产品
                ((ImageView) productHolder.getView(R.id.flag_img)).setVisibility(View.VISIBLE);
                ((ImageView) productHolder.getView(R.id.flag_img)).setImageResource(R.mipmap.miaosha);
                ((TextView) productHolder.getView(R.id.price_now)).setText(String.format("秒杀价:¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
                break;
            case 3:
                //限时购商品
                ((ImageView) productHolder.getView(R.id.flag_img)).setVisibility(View.VISIBLE);
                ((ImageView) productHolder.getView(R.id.flag_img)).setImageResource(R.mipmap.qianggou);
                ((TextView) productHolder.getView(R.id.price_now)).setText(String.format("抢购价:¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
                break;
        }

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.total_layout:
                        if (item.getStatus() == 1) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                            builder.setTitle("温馨提示");
                            builder.setMessage("该产品已下架！");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.show();
                        } else {
                            intent = new Intent(mContext, ProductDetailActivity.class);
                            intent.putExtra("productId", item.getProductId());
                            startActivity(intent);
                        }
                        break;
                    case R.id.btn_delete:
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setTitle("温馨提示");
                        builder.setMessage("确认删除商品吗？");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                deleteProduct(item.getProductId(), position);

                            }
                        });
                        builder.show();

                        break;
                }
            }
        };
        productHolder.setOnClickListener(R.id.total_layout, onClickListener);
        productHolder.setOnClickListener(R.id.btn_delete, onClickListener);
    }

    private void deleteProduct(long productId, final int position) {
        Call<ResultDO> call = ApiClient.getApiAdapter().deleteCollection(String.valueOf(productId), BaseApplication.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    dataSet.remove(position);
                    ToastUtils.showToast(mContext, "删除成功");
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<Product>>> call = ApiClient.getApiAdapter().getCollections(BaseApplication.getInstance().getMember().getId(), pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Product>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Product>>> call, Response<ResultDO<List<Product>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<Product>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }

                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Product>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
            }
        });
    }
}
